from flask import g, jsonify,send_from_directory
from flask import redirect,flash
from flask import render_template
from flask import request
from flask import session
from flask import url_for
import time
import json
import datetime
from datetime import datetime, timedelta
from order.utils.image_storage import storage
from order import db,path4,path3,path2,path1
from order.models import User, News,Order
from order.utils.common import user_login_data
from order.utils.response_code import RET
from . import admin_blue
from order.constants import *
import re
#查询所有订单
import random, string
def random_string1(slen=20):#截取长度不能超过指定序列的长度
    return ''.join(random.sample(string.ascii_letters + string.digits + '!@#$%^&*()_+=-', slen))
@admin_blue.route('/news_review')
@user_login_data
def news_review():
    # user = g.user
    # if not user or not user.is_admin:
    #     return redirect(url_for('admin.login'))
    try:
        p = int(request.args.get('p'))
    except:
        p = 1
    if 2>0:

        keywords = request.args.get('keywords')
        print(keywords)
        new_add = request.args.get('status_id')
        if keywords:

            if len(keywords.split('-'))!=3:
                if keywords=='dwqdwqdwfd':
                    paginate = Order.query.filter().order_by(Order.create_time.desc()).paginate(p,
                                                                                                ADMIN_NEWS_PAGE_MAX_COUNT,
                                                                                                False)
                else:
                    paginate = Order.query.filter(Order.staff_name==keywords).order_by(Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT,
                                                                                            False)
                if not paginate.items:


                    paginate = Order.query.filter(Order.ext1 == keywords).order_by(Order.create_time.desc()).paginate(p,
                                                                                                                  ADMIN_NEWS_PAGE_MAX_COUNT,                                                                                                          False)


            else:
                if len(keywords.split(' '))==2:

                    paginate = Order.query.filter(Order.jiedan_time == keywords + ' 00:00:00').order_by(
                        Order.create_time.desc()).paginate(
                        p, ADMIN_NEWS_PAGE_MAX_COUNT,
                        False)

                else:
                    paginate = Order.query.filter(Order.ext1 == keywords).order_by(
                        Order.create_time.desc()).paginate(
                        p, ADMIN_NEWS_PAGE_MAX_COUNT,
                        False)

        elif new_add:

            paginate = Order.query.filter(Order.status_id== new_add).order_by(Order.create_time.desc()).paginate(p,
                                                                                                                    ADMIN_NEWS_PAGE_MAX_COUNT,
                                                                                                          False)
        else:

            paginate = Order.query.filter().order_by(Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT,
                                                                                         False)
        news_items = paginate.items

        current_page = paginate.page
        total_page = paginate.pages

        news_list = []
        for news in news_items if news_items else []:
            news_list.append(news.to_dict())
        users = User.query.filter(User.is_admin!=2).all()
        if keywords:
            data = {
                'news_list': news_list,
                'current_page': current_page,
                'total_page': total_page,
                'users': users,
                'keyw':keywords,
            }

        else:
            data = {
                'news_list': news_list,
                'current_page': current_page,
                'total_page': total_page,
                'users': users,
                'keyw': 'dwqdwqdwfd',

            }

        if new_add=='1':
            return render_template('admin/add_new.html', data=data)
        return render_template('admin/all_orders_new.html', data=data)
    else:
        keywords = request.args.get('keywords')
        new_add = request.args.get('status_id')
        if keywords:
            paginate = Order.query.filter(Order.staff_name == keywords).filter(Order.ext2==g.user.nick_name).order_by(Order.create_time.desc()).paginate(p,
                                                                                                                    ADMIN_NEWS_PAGE_MAX_COUNT,
                                                                                                                    False)
            if not paginate.items:
                paginate = Order.query.filter(Order.ext1 == keywords).filter(Order.ext2==g.user.nick_name).order_by(Order.create_time.desc()).paginate(p,
                                                                                                                  ADMIN_NEWS_PAGE_MAX_COUNT,
                                                                                                                  False)

        elif new_add:
            paginate = Order.query.filter(Order.status_id == new_add).filter(Order.ext2==g.user.nick_name).order_by(Order.create_time.desc()).paginate(p,
                                                                                                                  ADMIN_NEWS_PAGE_MAX_COUNT,
                                                                                                                  False)
        else:
            paginate = Order.query.filter().filter(Order.ext2==g.user.nick_name).order_by(Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT,
                                                                                        False)
        news_items = paginate.items

        current_page = paginate.page
        total_page = paginate.pages

        news_list = []
        for news in news_items if news_items else []:
            news_list.append(news.to_dict())
        users=User.query.filter().all()
        data = {
            'news_list': news_list,
            'current_page': current_page,
            'total_page': total_page,
            'users':users,
        }
        if new_add == '1':
            return render_template('admin/add_new.html', data=data)
        return render_template('admin/all_orders_new.html', data=data)




@admin_blue.route('/add_new')
@user_login_data
def add_new():
    try:
        p = int(request.args.get('p'))
    except:
        p = 1
    if 2>0:
        keywords = request.args.get('keywords')
        if keywords:
            paginate = Order.query.filter(Order.staff_name==keywords and Order.status_id==1).filter(Order.jiedan_time==datetime.now().strftime('%Y-%m-%d')).order_by(Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT,False)
            if not paginate.items:
                paginate = Order.query.filter(Order.ext1 == keywords and Order.status_id==1).filter(Order.jiedan_time==datetime.now().strftime('%Y-%m-%d')).order_by(Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT,False)
        else:

            paginate = Order.query.filter(Order.jiedan_time==datetime.now().strftime('%Y-%m-%d') and Order.status_id==1).order_by(Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT,False)
        news_items = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
        news_list = []
        for news in news_items if news_items else []:
            news_list.append(news.to_dict())
        data = {
            'news_list': news_list,
            'current_page': current_page,
            'total_page': total_page,
            'user':g.user,
        }
        return render_template('admin/add_new.html', data=data)
    else:
        keywords = request.args.get('keywords')
        if keywords:
            paginate = Order.query.filter(Order.staff_name == keywords and Order.status_id == 1).filter(
                Order.jiedan_time == datetime.now().strftime('%Y-%m-%d')).filter(Order.ext2==g.user.nick_name).order_by(Order.create_time.desc()).paginate(p,
                                                                                                                      ADMIN_NEWS_PAGE_MAX_COUNT,
                                                                                                                      False)
            if not paginate.items:
                paginate = Order.query.filter(Order.ext1 == keywords and Order.status_id == 1).filter(
                    Order.jiedan_time == datetime.now().filter(Order.ext2==g.user.nick_name).strftime('%Y-%m-%d')).order_by(
                    Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT, False)
        else:

            paginate = Order.query.filter(
                Order.jiedan_time == datetime.now().strftime('%Y-%m-%d') and Order.status_id == 1).filter(Order.ext2==g.user.nick_name).order_by(
                Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT, False)
        news_items = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
        news_list = []
        for news in news_items if news_items else []:
            news_list.append(news.to_dict())
        data = {
            'news_list': news_list,
            'current_page': current_page,
            'total_page': total_page,
            'user': g.user,
        }
        return render_template('admin/add_new.html', data=data)



@admin_blue.route('/dsp')
@user_login_data
def dsp():
    try:
        p = int(request.args.get('p'))
    except:
        p = 1
    if 2>0:
        keywords = request.args.get('keywords')

        if keywords:

            paginate = Order.query.filter(Order.staff_name==keywords).filter(Order.status_id==2).order_by(Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT,False)
            if not paginate.items:
                paginate = Order.query.filter(Order.ext1 == keywords and Order.status_id==2).order_by(Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT,False)
        else:
            paginate = Order.query.filter(Order.status_id==2).order_by(Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT,False)
        news_items = paginate.items

        current_page = paginate.page
        total_page = paginate.pages

        news_list = []
        for news in news_items if news_items else []:
            news_list.append(news.to_dict())
        data = {
            'news_list': news_list,
            'current_page': current_page,
            'total_page': total_page,
        }
        return render_template('admin/dsp.html', data=data)
    else:
        keywords = request.args.get('keywords')
        if keywords:

            paginate = Order.query.filter(Order.staff_name == keywords and Order.status_id == 2).order_by(
                Order.create_time.desc()).filter(Order.ext2==g.user.nick_name).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT, False)
            if not paginate.items:
                paginate = Order.query.filter(Order.ext1 == keywords and Order.status_id == 2).filter(Order.ext2==g.user.nick_name).order_by(
                    Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT, False)
        else:

            paginate = Order.query.filter(Order.status_id == 2).filter(Order.ext2==g.user.nick_name).order_by(Order.create_time.desc()).paginate(p,
                                                                                                            ADMIN_NEWS_PAGE_MAX_COUNT,
                                                                                                            False)
        news_items = paginate.items

        current_page = paginate.page
        total_page = paginate.pages

        news_list = []
        for news in news_items if news_items else []:
            news_list.append(news.to_dict())
        data = {
            'news_list': news_list,
            'current_page': current_page,
            'total_page': total_page,
        }
        return render_template('admin/dsp.html', data=data)


@admin_blue.route('/djz')
@user_login_data
def djz():
    try:
        p = int(request.args.get('p'))
    except:
        p = 1
    if g.user.is_admin!=2:
        keywords = request.args.get('keywords')

        if keywords:

            paginate = Order.query.filter(Order.staff_name==keywords and Order.status_id==3).order_by(Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT,False)
            if not paginate.items:
                paginate = Order.query.filter(Order.ext1 == keywords and Order.status_id==3).order_by(Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT,False)
        else:

            paginate = Order.query.filter(Order.status_id==3).order_by(Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT,False)
        news_items = paginate.items

        current_page = paginate.page
        total_page = paginate.pages

        news_list = []
        for news in news_items if news_items else []:
            news_list.append(news.to_dict())
        data = {
            'news_list': news_list,
            'current_page': current_page,
            'total_page': total_page,
        }
        return render_template('admin/djz.html', data=data)
    else:
        keywords = request.args.get('keywords')

        if keywords:

            paginate = Order.query.filter(Order.staff_name == keywords and Order.status_id == 3).filter(Order.ext2==g.user.nick_name).order_by(
                Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT, False)
            if not paginate.items:
                paginate = Order.query.filter(Order.ext1 == keywords and Order.status_id == 3).filter(Order.ext2==g.user.nick_name).order_by(
                    Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT, False)
        else:

            paginate = Order.query.filter(Order.status_id == 3).filter(Order.ext2==g.user.nick_name).order_by(Order.create_time.desc()).paginate(p,
                                                                                                            ADMIN_NEWS_PAGE_MAX_COUNT,
                                                                                                            False)
        news_items = paginate.items

        current_page = paginate.page
        total_page = paginate.pages

        news_list = []
        for news in news_items if news_items else []:
            news_list.append(news.to_dict())
        data = {
            'news_list': news_list,
            'current_page': current_page,
            'total_page': total_page,
        }
        return render_template('admin/djz.html', data=data)


@admin_blue.route('/yjz')
@user_login_data
def yjz():
    try:
        p = int(request.args.get('p'))
    except:
        p = 1

    if g.user.is_admin!=2:
        keywords = request.args.get('keywords')

        if keywords:

            paginate = Order.query.filter(Order.staff_name==keywords and Order.status_id==4).order_by(Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT,False)
            if not paginate.items:
                paginate = Order.query.filter(Order.ext1 == keywords and Order.status_id==4).order_by(Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT,False)
        else:

            paginate = Order.query.filter(Order.status_id==4).order_by(Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT,False)
        news_items = paginate.items

        current_page = paginate.page
        total_page = paginate.pages

        news_list = []
        for news in news_items if news_items else []:
            news_list.append(news.to_dict())
        data = {
            'news_list': news_list,
            'current_page': current_page,
            'total_page': total_page,
        }
        return render_template('admin/yjz.html', data=data)
    else:
        keywords = request.args.get('keywords')

        if keywords:

            paginate = Order.query.filter(Order.staff_name == keywords and Order.status_id == 4).filter(Order.ext2==g.user.nick_name).order_by(
                Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT, False)
            if not paginate.items:
                paginate = Order.query.filter(Order.ext1 == keywords and Order.status_id == 4).filter(Order.ext2==g.user.nick_name).order_by(
                    Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT, False)
        else:

            paginate = Order.query.filter(Order.status_id == 4).filter(Order.ext2==g.user.nick_name).order_by(Order.create_time.desc()).paginate(p,
                                                                                                            ADMIN_NEWS_PAGE_MAX_COUNT,
                                                                                                            False)
        news_items = paginate.items

        current_page = paginate.page
        total_page = paginate.pages

        news_list = []
        for news in news_items if news_items else []:
            news_list.append(news.to_dict())
        data = {
            'news_list': news_list,
            'current_page': current_page,
            'total_page': total_page,
        }
        return render_template('admin/yjz.html', data=data)


@admin_blue.route('/user_list')
# @user_login_data
def user_list():
    # user = g.user
    # if not user or not user.is_admin:
    #     return redirect(url_for('admin.login'))
    try:
        p = int(request.args.get('p'))
    except:
        p = 1
    paginate = User.query.filter(User.is_admin!=1).order_by(User.last_login.desc()).paginate(p, ADMIN_USER_PAGE_MAX_COUNT, False)
    user_items = paginate.items
    current_page = paginate.page
    total_page = paginate.pages

    users = []
    for user in user_items if user_items else []:
        users.append(user.to_admin_dict())
    data = {
        'users': users,
        'current_page': current_page,
        'total_page': total_page,
    }
    return render_template('admin/user_list.html', data=data)


@admin_blue.route('/user_count')
# @user_login_data
def user_count():
    # user = g.user
    # if not user or not user.is_admin:
    #     return redirect(url_for('admin.login'))

    total_count = Order.query.filter().count()

    t = time.localtime()
    new_time_mon = '%0d-%02d-01' % (t.tm_year, t.tm_mon)
    mon_begin = datetime.strptime(new_time_mon, '%Y-%m-%d')
    mon_count = Order.query.filter(Order.status_id==1).count()
    djz=Order.query.filter(Order.status_id==3).count()
    yjz = Order.query.filter(Order.status_id == 4).count()

    new_time_today = "%d-%02d-%02d" % (t.tm_year, t.tm_mon, t.tm_mday)
    today_begin = datetime.strptime(new_time_today, '%Y-%m-%d')
    day_count = Order.query.filter(Order.status_id==2).count()

    active_date = []
    active_count = []
    for i in range(0, 31):
        begin_date = today_begin - timedelta(days=i)
        end_date = today_begin - timedelta(days=(i - 1))
        count = User.query.filter(User.is_admin == False, User.create_time >= begin_date,
                                  User.create_time < end_date).count()
        active_count.append(count)
        active_date.append(begin_date.strftime('%Y-%m-%d'))
    active_date.reverse()
    active_count.reverse()
    data = {
        'total_count': total_count,
        'mon_count': mon_count,
        'day_count': day_count,
        'djz':djz,
        'yjz':yjz,
        'qt':0,
        'active_count': active_count,
        'active_date': active_date,
    }

    return render_template('admin/user_count.html', data=data)

#退出登陆
@admin_blue.route('/logout')
@user_login_data
def logout():
    user = g.user
    if not user or not user.is_admin:
        return redirect(url_for('admin.login'))
    session.pop('user_mobile')
    session.pop('user_id')
    session.pop('user_is_admin')
    return redirect(url_for('admin.login'))



#用户登陆
@admin_blue.route('/login', methods=['GET', 'POST'])
@user_login_data
def login():
    if request.method == 'GET':
        # user = g.user
        # if user and user.is_admin:
        #     return redirect(url_for('admin.index'))
        return render_template('admin/login.html')
    username = request.form.get('username')
    password = request.form.get('password')
    if not all([username, password]):
        return render_template('admin/login.html', errmsg='请输入账户密码')
    user = User.query.filter(User.mobile == username).first()
    if not user:
        return render_template('admin/login.html', errmsg='用户不存在')
    if not user.check_password(password):
        return render_template('admin/login.html', errmsg='请输入正确的密码')
    session['user_id'] = user.id
    session['user_mobile'] = user.mobile
    session['user_is_admin'] = user.is_admin

    return render_template('admin/index.html',user=user)



#注册用户
@admin_blue.route('/reginst', methods=['GET', 'POST'])
# @user_login_data
def reginst():
    if request.method=='GET':
        return render_template('admin/user_add_new.html',message={'r':'必填','n':'必填','m':'必填'})
    nick_name=request.form.get('nick_name')
    mobile=request.form.get('mobile')
    password=request.form.get('password')
    repassword = request.form.get('repassword')
    action = request.form.get('action')
    reg = '^1(3[0-9]|4[5,7]|5[0,1,2,3,5,6,7,8,9]|6[2,5,6,7]|7[0,1,7,8]|8[0-9]|9[1,8,9])\d{8}$'
    print(nick_name,mobile,password,repassword)
    if not all([nick_name,mobile,password,repassword]):
        return render_template('admin/user_add_new.html',message={'r':'请填写所有信息','n':'必填','m':'必填'})
    elif len(mobile)!=11:
        return render_template('admin/user_add_new.html',message={'m':'请输入正确的手机号','n':'必填','r':'必填'})
    elif password!=repassword:
        return render_template('admin/user_add_new.html',message={'r':'两次密码不一样','m':'必填','n':'必填'})
    else:
        u=User.query.filter(User.nick_name==nick_name).first()
        u1=User.query.filter(User.mobile==mobile).first()
        if u:
            return render_template('admin/user_add_new.html',message={'n':'该用户名已被注册过','m':'必填','r':'必填'})
        if u1:
            return render_template('admin/user_add_new.html', message={'m':'该手机已被注册过','n':'必填','r':'必填'})
        user=User()
        if action=='1':
            user.is_admin=1
        elif action=='2':
            user.is_admin = 2
        else:
            user.is_admin = 0
        user.mobile = mobile
        user.nick_name = nick_name
        user.password = password
        db.session.add(user)
        db.session.commit()
        return render_template('admin/user_add_new.html',message={'m':'必填','n':'必填','r':'用户添加成功!'})

#
@admin_blue.route('/order_info', methods=['GET', 'POST'])
@user_login_data
def order_info():
    us_id=g.user.is_admin
    if us_id==1 or us_id==2:
        order_id=request.args.get('order_id')
        info_list=Order.query.filter(Order.id==order_id).first()
        return render_template('admin/order_detail.html', data=info_list)
    else:
        order_id = request.args.get('order_id')
        info_list = Order.query.filter(Order.id == order_id).first()
        if info_list.staff_name==g.user.nick_name:

            return render_template('admin/order_detail.html', data=info_list)
        else:
            return '您没有权限查看此订单!'

@admin_blue.route('/add_order', methods=['GET', 'POST'])
@user_login_data
def add_order():
    offer = User.query.filter(User.is_admin == 2).all()
    if request.method=='GET':
        return render_template('admin/add_order.html', data=offer)
    fn = random_string1()
    shop_name=request.form.get('shop_name')
    status_id=request.form.get('status_id')
    jiedan_time=request.form.get('jiedan_time')
    amount=request.form.get('amount')
    keywords=request.form.get('keywords')
    ASIN=request.form.get('ASIN')
    offer_name=request.form.get('offer_name')
    site_id=request.form.get('site_id')
    staff_name=g.user.nick_name
    ps=request.form.get('ps')
    item_picture=request.files.get('item_picture')
    num=request.form.get('order_num')
    seller_type=request.form.get('seller_type')
    if not all([offer,num,item_picture,staff_name,status_id,offer_name,ASIN,keywords,amount,jiedan_time,shop_name]):
        return '请填写所有的订单信息！'
    for i in range(int(num)):
        order=Order()
        order.status_id=int(status_id)
        order.jiedan_time=jiedan_time+' 00:00:00'
        order.amount=amount
        order.keywords=keywords
        order.ASIN=ASIN
        order.site_id=int(site_id)
        order.staff_name=staff_name
        order.seller_id=2
        order.item_picture=fn+item_picture.filename
        order.ps=ps
        order.shop_name=shop_name
        order.ext2=offer_name
        order.seller_id=int(seller_type)
        db.session.add(order)
        db.session.commit()
        #保存图片到本地
    path=os.path.join(path1,fn+item_picture.filename)
    item_picture.save(path)
    return render_template('admin/add_order.html',data=offer)


@admin_blue.route('/add_info', methods=['GET', 'POST'])
@user_login_data
def add_info():
    id=json.loads(request.get_data(as_text=True))['order_id']
    order_id=json.loads(request.get_data(as_text=True))['order']
    pldz=json.loads(request.get_data(as_text=True))['pldz']
    ddjt=json.loads(request.get_data(as_text=True))['ddjt']
    pljt=json.loads(request.get_data(as_text=True))['pljt']
    fkjt=json.loads(request.get_data(as_text=True))['fkjt']
    ps=json.loads(request.get_data(as_text=True))['ps']
    order = Order.query.filter(Order.id == int(id)).first()

    if order_id!='None':
        od_id = Order.query.filter(Order.ext1 == order_id).first()
        if not od_id:
            order.ext1=order_id
            order.status_id=2
            db.session.add(order)
            db.session.commit()
    elif pldz!='None':
        order.comment_url = pldz
        order.status_id = 3
        db.session.add(order)
        db.session.commit()
    elif ps!='None':
        print(ps)
        order.ps = ps
        db.session.add(order)
        db.session.commit()
    return jsonify(errno=RET.OK, errmsg='OK', data=None)



@admin_blue.route('/test_date/<order_id>', methods=['GET', 'POST'])
@user_login_data
def test_date(order_id):
    if request.method=='GET':
        return render_template('admin/test_date.html',data=None)
    file=request.files['file']
    fn=random_string1()
    order_id=int(order_id.split('h')[0])
    order=Order.query.filter(Order.id==order_id).first()
    order.order_picture=fn+file.filename
    order.status_id=2
    try:
        db.session.add(order)
        db.session.commit()
    except:
        db.session.rollback()
    path = os.path.join(path2, fn+file.filename)
    file.save(path)
    return jsonify(errno=RET.OK, errmsg='OK', data=None)


@admin_blue.route('/test_date1/<order_id>', methods=['GET', 'POST'])
@user_login_data
def test_date1(order_id):

    if request.method=='GET':
        return render_template('admin/test_date.html',data=None)
    file=request.files['file']
    fn = random_string1()
    order_id=int(order_id.split('h')[0])
    order=Order.query.filter(Order.id==order_id).first()
    order.comment_picture=fn+file.filename
    order.status_id=3
    try:
        db.session.add(order)
        db.session.commit()
    except:
        db.session.rollback()
    path = os.path.join(path3, fn+file.filename)
    file.save(path)
    return jsonify(errno=RET.OK, errmsg='OK', data=None)


@admin_blue.route('/test_date2/<order_id>', methods=['GET', 'POST'])
@user_login_data
def test_date2(order_id):
    if request.method=='GET':
        return render_template('admin/test_date.html',data=None)
    file=request.files['file']
    fn = random_string1()
    order_id=int(order_id.split('h')[0])
    order=Order.query.filter(Order.id==order_id).first()
    order.pay_picture=fn+file.filename
    order.status_id=4
    try:
        db.session.add(order)
        db.session.commit()
    except:
        db.session.rollback()
    path = os.path.join(path4, file.filename)
    file.save(path)
    return jsonify(errno=RET.OK, errmsg='OK', data=None)

@admin_blue.route('/fws_js', methods=['GET', 'POST'])
@user_login_data
def fws_js():
    try:
        p = int(request.args.get('p'))
    except:
        p = 1
    if 1>0:
        keywords = request.args.get('keywords')
        if keywords:
            if keywords=='dwqdwqdq':
                paginate = Order.query.filter(Order.status_id == 4).order_by(
                    Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT, False)
            else:
                paginate = Order.query.filter(Order.ext1==keywords and Order.status_id==4).order_by(Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT,False)
                if not paginate.items:
                    paginate = Order.query.filter(Order.ps.like('%'+keywords+'%')).filter(Order.status_id==4).order_by(Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT,False)

            news_items = paginate.items
            current_page = paginate.page
            total_page = paginate.pages
            news_list = []
            for news in news_items if news_items else []:
                news_list.append(news.to_dict())
            data = {
                'news_list': news_list,
                'current_page': current_page,
                'total_page': total_page,
                'keyw': keywords,
            }
            return render_template('admin/fws_js.html', data=data)
        else:
            paginate = Order.query.filter(Order.status_id==4).order_by(Order.create_time.desc()).paginate(p, ADMIN_NEWS_PAGE_MAX_COUNT,False)
            news_items = paginate.items

            current_page = paginate.page
            total_page = paginate.pages

            news_list = []
            for news in news_items if news_items else []:
                news_list.append(news.to_dict())
            data = {
                'news_list': news_list,
                'current_page': current_page,
                'total_page': total_page,
                'keyw':'dwqdwqdq',
            }
            return render_template('admin/fws_js.html', data=data)

@admin_blue.route('/password_reset', methods=['GET', 'POST'])
@user_login_data
def password_reset():
    print(g.user.id)
    if request.method=='GET':
        return render_template('admin/password_reset.html',message={'m':'','n':'','r':''})

    old_password=request.form.get('old_password')
    password=request.form.get('password')
    repassword=request.form.get('repassword')
    if not all([old_password,password,repassword]):
        return render_template('admin/password_reset.html', message={'m': '', 'n': '', 'r': '请输入所有信息！'})
    if not g.user.check_password(old_password):
        return render_template('admin/password_reset.html',message={'m':'','n':'','r':'旧密码错误，请重试!'})
    if password!=repassword:
        return render_template('admin/password_reset.html', message={'m': '', 'n': '', 'r': '两次密码不一致，请重试!'})
    if len(password)<6:
        return render_template('admin/password_reset.html', message={'m': '', 'n': '', 'r': '密码长度至少为6，请重试!'})
    if old_password==password:
        return render_template('admin/password_reset.html', message={'m': '', 'n': '', 'r': '新密码不能与旧密码相同，请重试!'})
    g.user.password=password
    try:
        db.session.add(g.user)
        db.session.commit()
    except:
        db.session.rollback()
        return render_template('admin/password_reset.html', message={'m': '', 'n': '', 'r': '密码修改失败，请重试!'})

    return render_template('admin/password_reset.html', message={'m': '', 'n': '', 'r': '密码修改成功!'})



@admin_blue.route('/del_order', methods=['GET', 'POST'])
@user_login_data
def del_order():
    order_id=request.args.get('order_id')
    order=Order.query.filter(Order.id==order_id).first()
    db.session.delete(order)
    db.session.commit()
    return redirect('/admin/add_new')

@admin_blue.route('/change_status', methods=['GET', 'POST'])
@user_login_data
def change_status():
    order_id=request.args.get('order_id')

    ids=order_id.split('@')[0]
    status=order_id.split('@')[1]
    order1=Order.query.filter(Order.id==int(ids)).first()
    print(ids,status)
    if status=='是':
        order1.ext3=1
        db.session.add(order1)
        db.session.commit()
    else:
        order1.ext3 = 0
        db.session.add(order1)
        db.session.commit()
    return redirect('/admin/fws_js')